//
//  YZSwinerySearchResultController.m
//  VET
//
//  Created by 刘文靖 on 2018/7/30.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZSwinerySearchResultController.h"
#import "YZSwineryModel.h"
#import "MJRefresh.h"
#import "YZSwineryListCell.h"
#import "YZActionSheet.h"
#import "YZPigGroupDocVC.h"
#import "YZRouter+AutoVC.h"
#import "YZPopupCustomView.h"
#import "YZPopupController.h"
#import "YZCreateNoteVC.h"
#import "YZWorkNoteModel.h"
#import "YZWorkbenchAPI.h"
#import "YZAutoFormHeader.h"
#import "YZSearchBar.h"
@interface YZSwinerySearchResultController ()<UITableViewDelegate,UITableViewDataSource,YZActionSheetDelegate,YZSwineryListCellDelegate,UISearchBarDelegate>
@property (strong, nonatomic) NSMutableArray<YZSwineryModel *> *dataSource;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) YZSwineryModel *selectedModel;
@property (strong, nonatomic) NSString *batchNo;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) YZSearchBar *searchBar;
@end

@implementation YZSwinerySearchResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColorWithHex(0xffffff);
    [self setupMainView];
    [self setupRefresh];
}

- (void)setupMainView{
    self.cancelBtn = [[UIButton alloc] init];
    [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelBtn setTitleColor:kColorWithHex(0x434343) forState:UIControlStateNormal];
    self.cancelBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
    [self.view addSubview:self.cancelBtn];
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(36, 18));
        make.left.offset(18);
        make.top.offset(11 + kStatusBarHeight);
    }];
    [self.view addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(kScreenWidth - 80, 36));
        make.left.mas_equalTo(self.cancelBtn.mas_right).offset(0);
        make.top.offset(kStatusBarHeight);
    }];
    @weakify(self)
    [[self.cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self loadNewData];
    }];
    self.tableView.mj_header = header;
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}

- (void)loadNewData{
    if (self.batchNo.length == 0) {
        [self.tableView.mj_header endRefreshing];
        return;
    }
    @weakify(self)
    [[YZSwineryModelAPI requestSwineryList:0 batchNo:self.batchNo] subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        self.dataSource = [YZSwineryModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData{
    //[self.tableView.mj_footer endRefreshing];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundView.backgroundColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.rowHeight = 163;
        [_tableView registerClass:[YZSwineryListCell class] forCellReuseIdentifier:@"YZSwineryListCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.offset(0);
            make.top.offset(64);
        }];
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZSwineryListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YZSwineryListCell"];
    cell.model = self.dataSource[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YZPigGroupDocVC * pigGroupVC = [YZPigGroupDocVC new];
    pigGroupVC.model = self.dataSource[indexPath.row];
    
    [[YZRouter sharedInstance] pushVC:pigGroupVC];
}

#pragma mark - YZSwineArchieveCellDelegate
- (void)cellDidClickManage:(YZSwineryListCell *)cell{
    YZSwineryModel *swinery = cell.model;
    NSArray *sheetTitles;
    if (swinery.isFinished) {
        sheetTitles = @[@"添加笔记",@"删除"];
    }else{
        sheetTitles = @[@"编辑修改",@"死淘登记",@"转入转出",@"结束批次",@"添加笔记",@"删除"];
    }
    YZActionSheet *sheet = [[YZActionSheet alloc] initWithTitle:nil sheetTitles:sheetTitles cancleBtnTitle:@"取消" sheetStyle:YZActionSheetDefault delegate:self];
    sheet.sheetHeight = 55;
    sheet.subtitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.subtitleColor = kColorWithHex(0x393939);
    sheet.lineColor = kColorWithHex(0xD9D9D9);
    sheet.cancleHeight = 55;
    sheet.bottomMarginHeight = 15;
    sheet.cancelTitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.cancelTitleColor = kColorWithHex(0x393939);
    self.selectedModel = cell.model;
    [sheet show];
}

#pragma mark - YZActionSheetDelegate
/**
 点击actionSheet代理方法
 
 @param actionSheet actionSheet
 @param buttonIndex index
 */
- (void)actionSheet:(YZActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            if (self.selectedModel.isFinished) {//已经结批
                YZCreateNoteVC *noteVC = [[YZCreateNoteVC alloc] init];
                NSMutableArray *archiveList = [NSMutableArray array];
                [archiveList addObject:[YZArchiveModel convertWithSwinery:self.selectedModel]];
                noteVC.archiveList = archiveList;
                
                [[YZRouter sharedInstance] pushVC:noteVC];
            }else{//编辑修改
                NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                [[YZRouter sharedInstance] yz_atuoPush:@"cardNewSwinery" params:@{@"params" : @{kURI : kURI, @"id" : swineryId}} itemClick:nil];
            }
        }
            break;
            
        case 1://死淘登记
        {
            if (self.selectedModel.isFinished){
                YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
                @weakify(self)
                [customView setupUIWithTitle:nil message:[NSString stringWithFormat:@"确定要删除%@猪群？删除后不可恢复当前猪群已记录信息。",self.selectedModel.batchNo] confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
                    
                    @strongify(self)
                    // 删除猪群
                    NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                    [[YZWorkbenchAPI deleteSwineryAPI:swineryId] subscribeError:^(NSError * _Nullable error) {
                        
                        @strongify(self)
                        [self.YZ_popupController dismiss];
                        
                    } completed:^{
                        
                        @strongify(self)
                        [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
                        [self.dataSource removeObject:self.selectedModel];
                        [self.tableView reloadData];
                        [self.YZ_popupController dismiss];
                    }];
                    
                } cancelHandler:^{
                    
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                }];
                [self.YZ_popupController presentContentView:customView];
            }else{
                // 死淘登记
                NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                [[YZRouter sharedInstance] yz_atuoPush:@"cardDeadSignSwinery" params:@{@"params" : @{@"id" : swineryId, @"batchNo" : self.selectedModel.batchNo}} itemClick:nil];
            }
        }
            
            break;
            
        case 2://转入转出
        {
            // 转入转出
            NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
            [[YZRouter sharedInstance] yz_atuoPush:@"cardTransferSwinery" params:@{@"params" : @{@"id" : swineryId, @"batchNo" : self.selectedModel.batchNo}} itemClick:nil];
        }
            
            break;
            
        case 3://结束批次
        {
            if (self.selectedModel.realQty > 0) {
                
                YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
                @weakify(self)
                [customView setupUIWithTitle:nil message:[NSString stringWithFormat:@"猪群%@实时存栏不为0， 不可进行结批操作！", self.selectedModel.batchNo] confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
                    
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                    
                } cancelHandler:^{
                    
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                }];
                [self.YZ_popupController presentContentView:customView];
            } else {
                
                // 结批
                NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                [[YZRouter sharedInstance] yz_atuoPush:@"cardFinishSwinery" params:@{@"params" : @{@"id" : swineryId, @"batchNo" : self.selectedModel.batchNo}} itemClick:nil];
            }
        }
            
            break;
            
        case 4://添加笔记
        {
            YZCreateNoteVC *noteVC = [[YZCreateNoteVC alloc] init];
            NSMutableArray *archiveList = [NSMutableArray array];
            [archiveList addObject:[YZArchiveModel convertWithSwinery:self.selectedModel]];
            noteVC.archiveList = archiveList;
            
            [[YZRouter sharedInstance] pushVC:noteVC];
            
        }
            break;
            
        case 5:{//删除
            
            YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
            @weakify(self)
            [customView setupUIWithTitle:nil message:[NSString stringWithFormat:@"确定要删除%@猪群？删除后不可恢复当前猪群已记录信息。",self.selectedModel.batchNo] confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
                
                @strongify(self)
                // 删除猪群
                NSString *swineryId = [@(self.selectedModel.swineryId) stringValue];
                [[YZWorkbenchAPI deleteSwineryAPI:swineryId] subscribeError:^(NSError * _Nullable error) {
                    
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                    
                } completed:^{
                    
                    @strongify(self)
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSwineryRefreshNotification object:nil];
                    [self.dataSource removeObject:self.selectedModel];
                    [self.tableView reloadData];
                    [self.YZ_popupController dismiss];
                }];
                
            } cancelHandler:^{
                
                @strongify(self)
                [self.YZ_popupController dismiss];
            }];
            [self.YZ_popupController presentContentView:customView];
        }
            break;
            
        default:
            break;
    }
}
- (void)actionSheetCancle:(YZActionSheet *)actionSheet{
    
}

#pragma mark - getter && setter
-(YZSearchBar *)searchBar{
    if (!_searchBar){
        _searchBar = [[YZSearchBar alloc] init];
        _searchBar.backgroundColor = [UIColor clearColor];
        _searchBar.delegate = self;
        //光标颜色
        _searchBar.cursorColor = kColorWithHex(0x32BE60);
        //TextField
        _searchBar.searchBarTextField.backgroundColor = kColorWithHex(0xFAFAFA);
        _searchBar.searchBarTextField.layer.cornerRadius = 10;
        _searchBar.searchBarTextField.layer.masksToBounds = YES;
        _searchBar.searchBarTextField.layer.borderColor = kColorWithHex(0xFAFAFA).CGColor;
        _searchBar.searchBarTextField.layer.borderWidth = 1.0;
        _searchBar.searchBarTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        _searchBar.searchBarTextField.placeholder = @"搜索";
        _searchBar.delegate = self;
        //去掉取消按钮灰色背景
        _searchBar.hideSearchBarBackgroundImage = YES;
        [_searchBar.searchBarTextField becomeFirstResponder];
    }
    return _searchBar;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.view endEditing:YES];
    self.batchNo = searchBar.text;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
}


@end
